package com.ftg.learn.code.utils;

import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.google.gson.Gson;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Data
@AllArgsConstructor
@Slf4j
public class AliDyUtil {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String signName;
    private String templateCode;

    /**
     * 发送短信验证码
     * @param phoneNumber 接收短信的手机号码
     * @param code 验证码
     * @return 发送结果
     */
    public String sendSms(String phoneNumber, String code) {
        try {
            // 创建配置
            Config config = new Config();
            config.accessKeyId = accessKeyId;
            config.accessKeySecret = accessKeySecret;
            config.endpoint = endpoint;

            // 创建客户端
            Client client = new Client(config);

            // 准备模板参数（JSON格式）
            Map<String, String> templateParamMap = new HashMap<>();
            templateParamMap.put("code", code);  // 设置验证码

            // 使用Gson生成JSON字符串
            Gson gson = new Gson();
            String templateParam = gson.toJson(templateParamMap);

            // 创建发送请求
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phoneNumber)
                    .setSignName(signName)
                    .setTemplateCode(templateCode)
                    .setTemplateParam(templateParam);

            // 发送短信
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, new RuntimeOptions());

            // 处理响应
            String resultCode = sendSmsResponse.getBody().getCode();
            log.info("短信发送结果：{}，请求ID：{}", resultCode, sendSmsResponse.getBody().getRequestId());
            if("OK".equals(resultCode)){
                return code;
            }
            return "PHONE_ERROR";
        } catch (TeaException error) {
            // 阿里云API异常
            log.error("短信发送失败 - API错误: {}", error.getMessage());
            log.error("诊断建议: {}", error.getData().get("Recommend"));
            return "API_ERROR";
        } catch (Exception e) {
            // 其他异常
            log.error("短信发送失败 - 系统错误: {}", e.getMessage(), e);
            return "SYSTEM_ERROR";
        }
    }

    // 重载方法，生成随机验证码
    public String sendSms(String phoneNumber) {
        // 生成6位随机验证码
        String code = String.format("%06d", (int)(Math.random() * 1000000));
        return sendSms(phoneNumber, code);
    }
}
